package com.hehao.reactorPractice;

import com.hehao.entity.ReactiveRepository;
import com.hehao.entity.ReactiveUserRepository;
import com.hehao.entity.User;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

/**
 * @Author Damon
 * @Date 2024/5/8 14:37
 */
public class RequestPractice {

    ReactiveRepository<User> repository = new ReactiveUserRepository();

//========================================================================================

    // TODO Create a StepVerifier that initially requests all values and expect 4 values to be received
    // 创建一个 StepVerifier，初始请求所有值，并期望接收到 4 个值
    StepVerifier requestAllExpectFour(Flux<User> flux) {
        return StepVerifier.create(flux)
                .thenRequest(Long.MAX_VALUE)
                .expectNextCount(4)
                .expectComplete();
    }

//========================================================================================

    // TODO Create a StepVerifier that initially requests 1 value and expects User.SKYLER then requests another value and expects User.JESSE then stops verifying by cancelling the source
    // 创建一个 StepVerifier，初始请求 1 个值，并期望接收到 User.SKYLER，然后请求另一个值并期望接收到 User.JESSE，然后通过取消源停止验证
    StepVerifier requestOneExpectSkylerThenRequestOneExpectJesse(Flux<User> flux) {
        return StepVerifier.create(flux, 1)
                .expectNext(User.SKYLER)
                .thenRequest(1)
                .expectNext(User.JESSE)
                .thenCancel();
    }

//========================================================================================

    // TODO Return a Flux with all users stored in the repository that prints automatically logs for all Reactive Streams signals
    // 返回一个包含存储在存储库中的所有用户的 Flux，自动打印所有反应式流信号
    Flux<User> fluxWithLog() {
        return repository.findAll().log();
    }

//========================================================================================

    // TODO Return a Flux with all users stored in the repository that prints "Starring:" at first, "firstname lastname" for all values and "The end!" on complete
    // 返回一个包含存储在存储库中的所有用户的 Flux，首先打印 "Starring:"，然后为所有值打印 "firstname lastname"，最后在完成时打印 "The end!"
    Flux<User> fluxWithDoOnPrintln() {
        return repository.findAll()
                .doOnSubscribe(sub -> System.out.println("Starring:"))
                .doOnNext(user -> System.out.println(user.getFirstname() + " " + user.getLastname()))
                .doOnComplete(() -> System.out.println("The end!"));
    }
}
